//
//  TTStatuesCache.swift
//  TTWeibo
//
//  Created by 陶宏路 on 16/8/1.
//  Copyright © 2016年 陶路路. All rights reserved.
//

import UIKit
let  deleteTime:Double = -60*6
class TTStatuesCache: NSObject {

    
    class func checkChache(sinceId: Int64, maxId: Int64,sucessBlock:(response:[[String: AnyObject]]?)->()){
        
        let result = TTStatuesCache.getChache(sinceId, maxId: maxId)
            
        if result?.count > 0{
            
            print("本地缓存")
            sucessBlock(response: result)
            
        }else{
            
//      网络请求
            
            TTNetworkingTools.sharedNetworkManager.loadHomeData(maxId, sinceId: sinceId, success: { (responseObject) -> () in
                
                guard let response = responseObject?["statuses"] as? [[String: AnyObject]] else{
                    
                    sucessBlock(response: nil)
                    return
                }
                
                sucessBlock(response: response)
                
                saveChache(response)
                
                }, failure: { (error) -> () in
                
                   sucessBlock(response: nil)
            })
        }
        
        
    }
    
//   获取缓存
    class func getChache(sinceId: Int64, maxId: Int64)->[[String: AnyObject]]?{
        
//        判断是否登录
        
        guard let userId = TTOAutoModel.sharedOautoModel.userModel?.uid else{
            print("用户没有登录")
            return nil
        }
        
        if sinceId <= 0 && maxId <= 0{
            
            print("第一次请求数据")
            
            return nil
        }
        
        var sql = ""
        
        sql += "SELECT * FROM T_SHStatus\n"
        sql += "WHERE userid=\(userId)\n"
        if sinceId > 0 {
            sql += "AND statusid>\(sinceId)\n"
        }
        if maxId > 0 {
            sql += "AND statusid<=\(maxId)\n"
        }
        sql += "ORDER BY statusid DESC\n"
        sql += "LIMIT 20"

         var tempArray:[[String: AnyObject]] = [[String: AnyObject]]()
        
        let result = TTSQLManager.manager.searchTable(sql)
        
        for dic in result{
            
            let dict = try! NSJSONSerialization.JSONObjectWithData(dic["status"] as! NSData, options: []) as! [String: AnyObject]
            
            tempArray.append(dict)
        }
        
        return tempArray
    }
    
    
//    保存数据
    
    class func saveChache(response:[[String: AnyObject]]){
        
        guard let userId = TTOAutoModel.sharedOautoModel.userModel?.uid else{
            
            print("没有登录")
            
            return
        }
        
        let sql = "INSERT OR REPLACE INTO T_SHStatus (statusid,userid,status) VALUES (?,?,?)"
        
        TTSQLManager.manager.queue.inTransaction { (db, rollback) -> Void in
            
            for dic in response{
                
                let statusId = dic["id"] as! NSNumber
                // 微博数据
                let status = try! NSJSONSerialization.dataWithJSONObject(dic, options: [])
                let result = db.executeUpdate(sql, withArgumentsInArray: [statusId,userId,status])
                
                if result{
                    
                    print("保存成功")
                }else{
                    
                    print("保存失败")
                    
                    rollback.memory = true
                }
                
            }
        }
    }
    
// 删除本地数据
    
    class func deleteChache() {
        
        let df = NSDateFormatter()
        
        let date = NSDate().dateByAddingTimeInterval(deleteTime)
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let realDate =  df.stringFromDate(date)

        let sql = "DELETE FROM T_SHStatus WHERE createtime<'\(realDate)'"
        
        TTSQLManager.manager.queue.inDatabase { (db) -> Void in
            
            let result = db.executeUpdate(sql, withArgumentsInArray: nil)
            
            if result{
                
                print("保存成功")
            }else{
                
                print("保存失败")
            }
        }
    }
}
